package com.mimo.common.configuration.broadcast;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import com.mimo.common.configuration.broadcast.event.NotificationEvent;
import com.mimo.common.configuration.broadcast.listener.EventListener;

/**
 * {@link https://github.com/spring-projects/spring-framework/issues/25649}
 * <p>
 * 由于Spring的事件消息分发在当前版本中存在如上bug，为了规避该bug在其他业务上的出现，故自行写了一套，以作自用。
 * 
 * @author Hongyu
 */
@Configuration(proxyBeanMethods = false)
public class MultiCastConfiguration {

  @Autowired
  private ApplicationContext ctx;

  /**
   * 要特别注意，考虑容器突然reload或者刚启动，都会对MultiCastRegistry的数据做清空
   * 
   * @param event
   */
  @SuppressWarnings({ "rawtypes", "unchecked" })
  @org.springframework.context.event.EventListener
  public void onContainerStarted(ApplicationStartedEvent event) {
    Map<String, EventListener> listeners = ctx.getBeansOfType(EventListener.class);
    if (!CollectionUtils.isEmpty(listeners)) {
      MultiCastRegistry.INSTANCE.clear();
      for (EventListener<? extends NotificationEvent> listener : listeners.values()) {
        MultiCastRegistry.INSTANCE.add(listener);
      }
    }
  }
}
